import { getPage } from '../../utils/config';
import api from '../../utils/api';
import { http, $toast, $empty, $loading, storage, Validate } from '../../utils/utils';
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        userNickName: '',
        avatar:''
    },

    /**
     * 会员名
     */
    userNickNameInput(e) {
        this.setData({
            userNickNameError: '',
            userNickName: $empty(e.detail)
        })
    },

    /**
     * 提交修改
     */
    userNickNameSubmit(e) {
        Validate.check(this, this.userNickNameValidate, e.detail.value, (res) => {
            if (res) {
                const { userInfo, userId, userName, avatar, sex } = this.data;
                http.post(api.default, {
                    data: {
                        action: 'updateuserinfo',
                        userid: userId,
                        userName: userName,
                        nickname: e.detail.value.userNickName,
                        sex: sex,
                        birthday: '',
                        head_img: avatar,
                    }
                }).then((res) => {
                    userInfo.data.user = res.data.data;
                    storage.set('userInfo', userInfo);
                    $toast('修改成功', {
                        icon: 'success'
                    });
                    const pages = getCurrentPages()[getCurrentPages().length - 2];
                    wx.navigateBack({
                        delta: 1,
                        success() {
                            if (pages !== undefined || pages !== null) {
                                pages.data.pageChange = 1;
                                pages.onLoad();
                            }
                        }
                    });
                });
            }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        app.getLogin().then((res) => {
            this.setData({
                userInfo: res,
                logged: res.code,
                userName: res.data.user.user_name,
                userNickName:res.data.user.nickname,
                userId: res.data.user.user_id,
                sex: res.data.user.sex,
            });
        })

        /**
         * 收货地址保存
         */
        Validate.rules('#userNickName', (res) => {
            this.userNickNameValidate = res;
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    }
})